package top.fangw.oauth.service.impl;


import jakarta.annotation.Resource;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import top.fangw.common.api.openfign.admin.IUserServiceFeign;
import top.fangw.common.api.vo.UserVo;
import top.fangw.common.core.result.Result;
import top.fangw.oauth.model.OauthUser;
import top.fangw.oauth.model.SysUserEntity;

import java.util.Objects;


/**
 * @author fgw
 * @description
 * @createDate 2024/2/21
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private IUserServiceFeign userServiceFeign;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return buildDefaultUser();
    }
    public UserDetails loadUserByUsernameAndTenantId(String username,String  tenantId) throws UsernameNotFoundException{
        Result<UserVo> userVoResult = userServiceFeign.selectByUsernameAndTenantId(username, tenantId);
        if(userVoResult.getStatus()){
            UserVo data = userVoResult.getData();
            if(Objects.nonNull(data)){
                return new OauthUser(data);
            }
        }
       return buildDefaultUser();
    }

    private OauthUser buildDefaultUser(){
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        SysUserEntity sysUserEntity = new SysUserEntity();
        sysUserEntity.setId(Integer.valueOf("123456"));
        sysUserEntity.setUsername("MYH");
        sysUserEntity.setName("MYH");
        sysUserEntity.setPassword(encoder.encode("123456"));
        return new OauthUser(sysUserEntity);
    }

}
